/*
   Copyright 2011 James Bowling

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.armedia.dctm.constraints;

import static com.armedia.dctm.constraints.ConstraintUtils.getAttrIndex;
import static com.armedia.dctm.constraints.ConstraintUtils.isNull;
import static com.armedia.dctm.constraints.DqlUtils.executeSelectCountQuery;
import static com.armedia.dctm.constraints.DqlUtils.getDqlValueLiteral;

import org.apache.log4j.Logger;

import com.documentum.fc.client.IDfPersistentObject;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfType;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfLogger;
import com.documentum.fc.common.IDfAttr;
import com.documentum.fc.common.IDfId;
import com.documentum.fc.common.IDfValue;

public class ForeignKeyConstraintImpl implements Constraint {
	
	private static final ConstraintType CONSTRAINT_TYPE = ConstraintType.FOREIGN_KEY;
	
	private static final Logger LOGGER = DfLogger.getLogger(ForeignKeyConstraintImpl.class);

	private String typeName;
	
	private String attributeName;
	
	private String referencedTypeName;
	
	private String referencedAttributeName;
	
	private boolean mandatory;
	
	public ForeignKeyConstraintImpl(final String typeName, final String attributeName, 
			final String referencedTypeName, final String referencedAttributeName, final boolean mandatory) {
		super();
		if (typeName == null || typeName.length() == 0) {
			throw new IllegalArgumentException("typeName argument must not be null.");
		}
		if (attributeName == null || attributeName.length() == 0) {
			throw new IllegalArgumentException("singleTimeAttributeName argument must not be null.");
		}
		this.typeName = typeName;
		this.attributeName = attributeName;
		this.referencedTypeName = referencedTypeName;
		this.referencedAttributeName = referencedAttributeName;
		this.mandatory = mandatory;
	}

	public void check(IDfPersistentObject persistentObject) throws DfException {
		final IDfId objectId = persistentObject.getObjectId();
		LOGGER.debug(
			String.format("checking foreign key constraints for [%s.%s] id ['%s'].", 
			this.typeName, this.attributeName, objectId.getId())
		);
		final IDfSession session = persistentObject.getSession();
		final IDfType type = session.getType(typeName);
		final int attrIndex = getAttrIndex(type, this.attributeName);
		final IDfAttr attr = persistentObject.getAttr(attrIndex);
		if (attr.getDataType() != IDfValue.DF_BOOLEAN) { // we don't enforce foreign key for boolean types
			boolean isNull = false;		
			if (attr.isRepeating()) {		
				final int valueCount = persistentObject.getValueCount(attr.getName());
				if (valueCount > 0) {
					final StringBuffer criteriaBuffer = new StringBuffer();				
					for (int i = 0; i < valueCount; i++) {
						final IDfValue value = persistentObject.getRepeatingValue(attr.getName(), i);				
						isNull = isNull(persistentObject, attr, i);
						// null values are not permitted for repeating attributes
						if (isNull) {
							String format = "%s violation for object [%s] attribute [%s] at index [%s], value cannot be null";
							String msg = String.format(format, this.toString(), objectId.getId(), attr.getName(), i);
							throw new ForeignKeyConstraintException(this.typeName, this.attributeName, msg);								
						} else {
							final String dqlValueLiteral = getDqlValueLiteral(value);
							if (criteriaBuffer.length() > 0) {
								criteriaBuffer.append(" and ");
							}							
							final IDfType referencedType = session.getType(this.referencedTypeName);
							int referencedAttributeIndex = getAttrIndex(referencedType, referencedAttributeName);
							final IDfAttr referencedAttrib = referencedType.getTypeAttr(referencedAttributeIndex);
							// a repeating attribute can reference either a single or repeating attribute								
							if (referencedAttrib.isRepeating()) {
								final String attributeCriteria = String.format("any %s = %s", this.referencedAttributeName, dqlValueLiteral);
								criteriaBuffer.append(attributeCriteria);
							} else {
								final String attributeCriteria = String.format("%s = %s", this.referencedAttributeName, dqlValueLiteral);
								criteriaBuffer.append(attributeCriteria);				
							}							
						}
					}
					if (criteriaBuffer.length() > 0) {
						final String dql = String.format("select count(%s) from %s where %s", this.referencedAttributeName, this.referencedTypeName, criteriaBuffer.toString());
						final int count = executeSelectCountQuery(session, dql);
						if (count != valueCount) {
							String format = "%s violation for object [%s] attribute [%s]";
							String msg = String.format(format, this.toString(), objectId.getId(), attr.getName());
							throw new ForeignKeyConstraintException(this.typeName, this.attributeName, msg);					
							
						}						
					}
				}
			} else {
				final IDfValue value = persistentObject.getValue(attr.getName());
				isNull = isNull(persistentObject, attr);
				if (isNull) {
					if (mandatory) {
						String format = "%s violation for object [%s] attribute [%s], value [%s]";
						String msg = String.format(format, this.toString(), objectId.getId(), attr.getName(), value.toString());
						throw new ForeignKeyConstraintException(this.typeName, this.attributeName, msg);					
					}
				} else {
					final String dqlValueLiteral = getDqlValueLiteral(value);
					final String singleValuedForeignKeyQuery = "select count(*) from %s where %s = %s";
					final String dql = String.format(singleValuedForeignKeyQuery, referencedTypeName, referencedAttributeName, dqlValueLiteral);
					final int count = executeSelectCountQuery(session, dql);
					if (count == 0) {
						String format = "%s violation for object [%s] attribute [%s] value [%s].  Value not found in %s.%s";
						String msg = String.format(format, this.toString(), objectId.getId(), attr.getName(), value.toString(), referencedTypeName, referencedAttributeName);
						throw new ForeignKeyConstraintException(this.typeName, this.attributeName, msg);					
					}				
				}
			}				
		}
	
	}

	public void checkAll(IDfSession session) throws DfException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String toString() {
		final String format = "%s %s constraint for %s.%s";
		final String string = String.format(format, 
			this.mandatory ? "Mandatory" : "Non-Mandatory",				
			ForeignKeyConstraintImpl.CONSTRAINT_TYPE, 
			this.typeName, 
			this.attributeName
		);
		return string;
	}	

}
